import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:grint/bloc/content_curator_cubit.dart';
import 'package:grint/constant/icon_font.dart';
import 'package:grint/entity/content_submission.dart';
import 'package:grint/widget/black_button.dart';
import 'package:grint/widget/my_text.dart';
import '../../constant/colors.dart';
import '../../utils/whisper.dart';
import '../../utils/time_reminder_service.dart';
import '../../utils/local_store.dart';

class DiscoveryPage extends StatefulWidget {
  const DiscoveryPage({super.key});

  @override
  State<DiscoveryPage> createState() => _DiscoveryPageState();
}

class _DiscoveryPageState extends State<DiscoveryPage> {
  TimeOfDay _morningTime = const TimeOfDay(hour: 8, minute: 0);
  TimeOfDay _eveningTime = const TimeOfDay(hour: 19, minute: 0);

  bool _morningSwitch = false;
  bool _eveningSwitch = false;

  int _protectedDays = 2;
  final TimeReminderService _timeReminderService = TimeReminderService();

  @override
  void initState() {
    super.initState();
    _loadSettings();
    _timeReminderService.startTimeCheck();
  }

  Future<void> _loadSettings() async {
    await LocalStore().init();

    // 加载开关状态
    _morningSwitch = LocalStore().getFlagValue(
      'morning_switch',
      defaultValue: false,
    );
    _eveningSwitch = LocalStore().getFlagValue(
      'evening_switch',
      defaultValue: false,
    );

    // 加载时间设置
    final morningHour = LocalStore().getNumberValue(
      'morning_hour',
      defaultValue: 8,
    );
    final morningMinute = LocalStore().getNumberValue(
      'morning_minute',
      defaultValue: 0,
    );
    _morningTime = TimeOfDay(hour: morningHour, minute: morningMinute);

    final eveningHour = LocalStore().getNumberValue(
      'evening_hour',
      defaultValue: 19,
    );
    final eveningMinute = LocalStore().getNumberValue(
      'evening_minute',
      defaultValue: 0,
    );
    _eveningTime = TimeOfDay(hour: eveningHour, minute: eveningMinute);

    // 更新全局服务
    _timeReminderService.updateMorningReminder(_morningSwitch, _morningTime);
    _timeReminderService.updateEveningReminder(_eveningSwitch, _eveningTime);

    setState(() {});
  }

  Future<void> _saveSettings() async {
    // 保存开关状态
    await LocalStore().setFlagValue('morning_switch', _morningSwitch);
    await LocalStore().setFlagValue('evening_switch', _eveningSwitch);

    // 保存时间设置
    await LocalStore().setNumberValue('morning_hour', _morningTime.hour);
    await LocalStore().setNumberValue('morning_minute', _morningTime.minute);
    await LocalStore().setNumberValue('evening_hour', _eveningTime.hour);
    await LocalStore().setNumberValue('evening_minute', _eveningTime.minute);
  }

  @override
  void dispose() {
    // 不要在这里停止时间检查，因为需要在全局保持监听
    super.dispose();
  }

  Future<void> _selectTime(BuildContext context, bool isMorning) async {
    final TimeOfDay? picked = await showTimePicker(
      context: context,
      initialTime: isMorning ? _morningTime : _eveningTime,
    );

    if (picked != null) {
      setState(() {
        if (isMorning) {
          _morningTime = picked;
          if (_morningSwitch) {
            _timeReminderService.updateMorningReminder(true, picked);
          }
        } else {
          _eveningTime = picked;
          if (_eveningSwitch) {
            _timeReminderService.updateEveningReminder(true, picked);
          }
        }
      });
      _saveSettings();
    }
  }

  void _handleSwitchChange(bool value, bool isMorning) {
    setState(() {
      if (isMorning) {
        _morningSwitch = value;
        _timeReminderService.updateMorningReminder(value, _morningTime);
        if (value) {
          Whisper.breath(
            'You will be reminded to brush your teeth in the morning.',
          );
        }
      } else {
        _eveningSwitch = value;
        _timeReminderService.updateEveningReminder(value, _eveningTime);
        if (value) {
          Whisper.breath(
            'You will be reminded to brush your teeth in the evening.',
          );
        }
      }
    });
    _saveSettings();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.lightBlue,
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/commonBg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: SingleChildScrollView(
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 16.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Center(
                    child: Padding(
                      padding: EdgeInsets.only(bottom: 16.h),
                      child: Text(
                        'Grint',
                        style: TextStyle(
                          fontSize: 28.sp,
                          fontWeight: FontWeight.bold,
                          fontFamily: 'Rubik One',
                          color: Colors.black87,
                        ),
                      ),
                    ),
                  ),

                  Container(
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(30.r),
                      border: Border.all(color: AppColors.border, width: 3),
                    ),
                    padding: EdgeInsets.symmetric(
                      horizontal: 20.w,
                      vertical: 16.h,
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        _buildTimeRow(
                          time: _morningTime,
                          icon: 'assets/images/taiyang.png',
                          isMorning: true,
                        ),

                        Divider(
                          height: 24.h,
                          thickness: 0.5,
                          color: AppColors.textGrey.withAlpha(150),
                        ),

                        _buildTimeRow(
                          time: _eveningTime,
                          icon: 'assets/images/yueliang.png',
                          isMorning: false,
                        ),
                      ],
                    ),
                  ),

                  SizedBox(height: 16.h),

                  GestureDetector(
                    onTap: () {
                      context.push('/discovery/challenge');
                    },
                    child: Container(
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(30.r),
                        border: Border.all(color: AppColors.border, width: 3),
                      ),
                      padding: EdgeInsets.symmetric(
                        horizontal: 20.w,
                        vertical: 16.h,
                      ),
                      child: Row(
                        children: [
                          Image.asset(
                            'assets/images/guanjun.png',
                            width: 94.w,
                            height: 94.w,
                          ),
                          SizedBox(width: 12.w),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              MyText(
                                text: 'Daily',
                                type: TextType.miSans,
                                fontSize: 26.sp,
                                color: AppColors.black,
                                fontWeight: FontWeight.w900,
                              ),
                              MyText(
                                text: 'Challenge',
                                type: TextType.miSans,
                                fontSize: 26.sp,
                                color: AppColors.black,
                                fontWeight: FontWeight.w900,
                              ),
                            ],
                          ),
                          const Spacer(),
                          BlackButton(
                            icon: IconFontIcons.iconArrowRight,
                            onTap: () {
                              context.push('/discovery/challenge');
                            },
                          ),
                        ],
                      ),
                    ),
                  ),

                  SizedBox(height: 16.h),

                  Container(
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(30.r),
                      border: Border.all(color: AppColors.border, width: 3),
                    ),
                    padding: EdgeInsets.symmetric(
                      horizontal: 20.w,
                      vertical: 16.h,
                    ),

                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            MyText(
                              text: 'Daily Record',
                              type: TextType.miSans,
                              fontSize: 18.sp,
                              color: AppColors.black,
                              fontWeight: FontWeight.w900,
                            ),
                            SizedBox(width: 10.w),
                            MyText(
                              text: 'Maintain good habits',
                              type: TextType.miSans,
                              fontSize: 14.sp,
                              color: Color(0xFF161D1B),
                              fontWeight: FontWeight.w300,
                            ),
                          ],
                        ),
                        SizedBox(height: 10.h),

                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.baseline,
                              textBaseline: TextBaseline.alphabetic,
                              children: [
                                Text(
                                  _protectedDays.toString().padLeft(2, '0'),
                                  style: TextStyle(
                                    fontSize: 26.sp,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                                SizedBox(width: 5.w),
                                Text(
                                  'Day',
                                  style: TextStyle(
                                    fontSize: 14.sp,
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                              ],
                            ),

                            ElevatedButton(
                              onPressed: () {
                                context.push('/discovery/record');
                              },
                              style: ElevatedButton.styleFrom(
                                backgroundColor: AppColors.blue,
                                padding: EdgeInsets.symmetric(
                                  horizontal: 16.w,
                                  vertical: 10.h,
                                ),
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(24.r),
                                ),
                                elevation: 0,
                              ),
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Icon(
                                    IconFontIcons.iconCalendar,
                                    size: 18.sp,
                                    color: AppColors.black,
                                  ),
                                  SizedBox(width: 8.w),
                                  MyText(
                                    text: 'Check In',
                                    type: TextType.miSans,
                                    fontSize: 16.sp,
                                    color: AppColors.black,
                                    fontWeight: FontWeight.w800,
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),

                  Padding(
                    padding: EdgeInsets.only(
                      top: 16.h,
                      bottom: 16.h,
                      left: 6.w,
                    ),
                    child: Image.asset(
                      'assets/images/share-title.png',
                      height: 32.h,
                      fit: BoxFit.contain,
                    ),
                  ),

                  _buildShareItem(),

                  SizedBox(height: 100.h),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildTimeRow({
    required TimeOfDay time,
    required String icon,
    required bool isMorning,
  }) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Image.asset(icon, width: 50.w, height: 50.w),
            SizedBox(width: 12.w),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                GestureDetector(
                  onTap: () => _selectTime(context, isMorning),
                  child: Row(
                    children: [
                      Text(
                        '${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}',
                        style: TextStyle(
                          fontSize: 24.sp,
                          fontWeight: FontWeight.bold,
                          fontFamily: 'Rubik One',
                        ),
                      ),
                      SizedBox(width: 5.w),
                      Icon(
                        IconFontIcons.iconEdit,
                        size: 22.sp,
                        color: Colors.grey,
                      ),
                    ],
                  ),
                ),
                Text(
                  '≥2 Mins',
                  style: TextStyle(fontSize: 12.sp, color: Colors.black54),
                ),
              ],
            ),
          ],
        ),

        Transform.scale(
          scale: 0.8,
          child: Switch(
            value: isMorning ? _morningSwitch : _eveningSwitch,
            onChanged: (value) => _handleSwitchChange(value, isMorning),
            activeColor: AppColors.tabBlue,
            activeTrackColor: AppColors.blue.withAlpha(125),
            inactiveThumbColor: Colors.white,
            inactiveTrackColor: Colors.grey.withAlpha(75),
          ),
        ),
      ],
    );
  }

  Widget _buildShareItem() {
    return BlocBuilder<ContentCuratorCubit, ContentCuratorState>(
      builder: (context, state) {
        if (state.isProcessing) {
          return Center(
            child: Padding(
              padding: EdgeInsets.all(32.w),
              child: CircularProgressIndicator(color: AppColors.blue),
            ),
          );
        }

        if (state.submissions.isEmpty) {
          return Center(
            child: Padding(
              padding: EdgeInsets.all(32.w),
              child: MyText(
                text: 'No content available yet',
                type: TextType.miSans,
                fontSize: 16.sp,
                color: AppColors.textGrey,
              ),
            ),
          );
        }

        return Column(
          children:
              state.submissions.map((submission) {
                return GestureDetector(
                  onTap:
                      () => context.push(
                        '/discovery/share/${submission.submissionId}',
                      ),
                  child: Container(
                    margin: EdgeInsets.only(bottom: 16.h),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(20.r),
                      border: Border.all(color: AppColors.border, width: 3),
                    ),
                    padding: EdgeInsets.all(16.w),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            GestureDetector(
                              onTap: () => _navigateToUserProfile(submission),
                              child: Row(
                                children: [
                                  _buildUserAvatar(submission.authorAvatar),
                                  SizedBox(width: 12.w),
                                  Text(
                                    submission.authorName,
                                    style: TextStyle(
                                      fontSize: 16.sp,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            const Spacer(),
                            Container(
                              width: 36.w,
                              height: 36.w,
                              decoration: BoxDecoration(
                                color: AppColors.blue,
                                borderRadius: BorderRadius.circular(10.r),
                              ),
                              child: Center(
                                child: Icon(
                                  Icons.arrow_forward,
                                  size: 22.sp,
                                  color: Colors.white,
                                ),
                              ),
                            ),
                          ],
                        ),
                        SizedBox(height: 12.h),

                        Text(
                          submission.textDescription.isNotEmpty
                              ? submission.textDescription
                              : 'Shared a moment',
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: Colors.black87,
                          ),
                        ),
                        SizedBox(height: 12.h),

                        _buildSubmissionMediaContent(submission),

                        SizedBox(height: 12.h),

                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [
                                Icon(
                                  IconFontIcons.iconReport,
                                  size: 18.sp,
                                  color: AppColors.black,
                                ),
                                SizedBox(width: 8.w),
                                MyText(
                                  text: 'Report',
                                  type: TextType.miSans,
                                  color: AppColors.black,
                                  fontWeight: FontWeight.w800,
                                ),
                              ],
                            ),
                            Row(
                              children: [
                                Icon(
                                  IconFontIcons.iconCollect,
                                  size: 18.sp,
                                  color: AppColors.black,
                                ),
                                SizedBox(width: 6.w),
                                MyText(
                                  text: '${submission.appreciationCount}',
                                  type: TextType.miSans,
                                  color: AppColors.black,
                                  fontWeight: FontWeight.w800,
                                ),
                                SizedBox(width: 16.w),
                                Icon(
                                  IconFontIcons.iconComment,
                                  size: 16.sp,
                                  color: AppColors.black,
                                ),
                                SizedBox(width: 4.w),
                                MyText(
                                  text: '0', // 暂时显示0，后续可以添加评论功能
                                  type: TextType.miSans,
                                  color: AppColors.black,
                                  fontWeight: FontWeight.w800,
                                ),
                              ],
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                );
              }).toList(),
        );
      },
    );
  }

  Widget _buildUserAvatar(String avatarPath) {
    if (avatarPath.startsWith('/') || avatarPath.contains('Documents')) {
      return CircleAvatar(
        radius: 20.r,
        backgroundImage: FileImage(File(avatarPath)),
        onBackgroundImageError: (exception, stackTrace) {},
      );
    } else {
      return CircleAvatar(
        radius: 20.r,
        backgroundImage: AssetImage(avatarPath),
      );
    }
  }

  Widget _buildSubmissionMediaContent(ContentSubmission submission) {
    final mediaAssets = submission.mediaAssets;
    final double contentHeight = 180.h;

    if (mediaAssets.isEmpty) {
      return Container(
        height: contentHeight,
        decoration: BoxDecoration(
          color: AppColors.blue.withValues(alpha: 0.1),
          borderRadius: BorderRadius.circular(8.r),
        ),
        child: Center(
          child: Icon(
            Icons.image_not_supported,
            color: AppColors.textGrey,
            size: 48.w,
          ),
        ),
      );
    }

    switch (mediaAssets.length) {
      case 1:
        return SizedBox(
          height: contentHeight,
          child: _buildSubmissionMediaItem(mediaAssets[0]),
        );

      case 2:
        return SizedBox(
          height: contentHeight,
          child: Row(
            children: [
              Expanded(child: _buildSubmissionMediaItem(mediaAssets[0])),
              SizedBox(width: 8.w),
              Expanded(child: _buildSubmissionMediaItem(mediaAssets[1])),
            ],
          ),
        );

      case 3:
      default:
        return SizedBox(
          height: contentHeight,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Expanded(
                flex: 2,
                child: _buildSubmissionMediaItem(mediaAssets[0]),
              ),
              SizedBox(width: 8.w),
              Expanded(
                child: Column(
                  children: [
                    Expanded(child: _buildSubmissionMediaItem(mediaAssets[1])),
                    SizedBox(height: 8.h),
                    if (mediaAssets.length > 2)
                      Expanded(child: _buildSubmissionMediaItem(mediaAssets[2]))
                    else
                      Expanded(child: Container()),
                  ],
                ),
              ),
            ],
          ),
        );
    }
  }

  Widget _buildSubmissionMediaItem(MediaAsset mediaAsset) {
    final isVideo = mediaAsset.mediaType == ContentMediaType.videoClip;
    final imagePath = isVideo ? mediaAsset.thumbnailPath : mediaAsset.localPath;

    return ClipRRect(
      borderRadius: BorderRadius.circular(8.r),
      child: Stack(
        fit: StackFit.expand,
        children: [
          if (imagePath != null)
            _buildImageWidget(imagePath)
          else
            Container(
              color: AppColors.blue.withValues(alpha: 0.1),
              child: Center(
                child: Icon(
                  Icons.image_not_supported,
                  color: AppColors.textGrey,
                  size: 32.w,
                ),
              ),
            ),

          if (isVideo)
            Center(
              child: Icon(
                IconFontIcons.iconPlay,
                color: Colors.white,
                size: 40.sp,
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildImageWidget(String imagePath) {
    if (imagePath.startsWith('/') ||
        imagePath.contains('Documents') ||
        imagePath.contains('thumbnails')) {
      return Image.file(
        File(imagePath),
        fit: BoxFit.cover,
        errorBuilder: (context, error, stackTrace) {
          return Container(
            color: AppColors.blue.withValues(alpha: 0.1),
            child: Center(
              child: Icon(
                Icons.image_not_supported,
                color: AppColors.textGrey,
                size: 32.w,
              ),
            ),
          );
        },
      );
    } else {
      return Image.asset(
        imagePath,
        fit: BoxFit.cover,
        errorBuilder: (context, error, stackTrace) {
          return Container(
            color: AppColors.blue.withValues(alpha: 0.1),
            child: Center(
              child: Icon(
                Icons.image_not_supported,
                color: AppColors.textGrey,
                size: 32.w,
              ),
            ),
          );
        },
      );
    }
  }

  void _navigateToUserProfile(ContentSubmission submission) {
    context.push('/profile/others/${submission.authorId}');
  }
}
